#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/11/1 16:10
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : mid_ip_location.py
# @Software: PyCharm
# @Desc    :
from django.utils.deprecation import MiddlewareMixin
from common.models import AccessLog
from common.utils.util_ip import get_ip_location

class AccessLogMiddleware(MiddlewareMixin):
    """访问日志中间件：自动记录IP及定位信息"""
    def process_request(self, request):
        # 1. 获取访问IP
        ip = request.META.get('REMOTE_ADDR', '未知IP')
        # 2. 跳过内部接口（避免循环记录）
        if request.path.startswith('/api/'):
            return
        # 3. 获取IP定位信息
        location = get_ip_location(ip)
        # 4. 保存访问记录
        AccessLog.objects.create(
            ip=ip,
            city=location["city"],
            region=location["region"],
            longitude=location["longitude"],
            latitude=location["latitude"],
            user_agent=request.META.get('HTTP_USER_AGENT', '')
        )